import {json} from "@remix-run/node";
import {authenticate} from "../shopify.server";
import {
  Badge,
  Card,
  IndexFilters,
  IndexTable,
  Page,
  TabProps,
  useIndexResourceState,
  useSetIndexFiltersMode,
} from "@shopify/polaris";
import {Range, SelectionType} from "@shopify/polaris/build/ts/src/utilities/index-provider/types";
import {useEffect, useState} from "react";
import axios from "axios";

export async function loader({request}) {
  const {admin, session} = await authenticate.admin(request);

  const response1 = await admin.rest.resources.Order.all({
    session: session,
    status: "any",
  });
  const shopifyOrderList = response1?.data || [];

  const response2 = await axios.get('http://127.0.0.1:8123/api/shopify/queryOrderSyncList');
  const resDataList = response2.data.data || [];


  resDataList.forEach(bizOrderItem => {
    shopifyOrderList.forEach(shopifyOrderItem => {
      if (bizOrderItem.id == shopifyOrderItem.id) {
        bizOrderItem.oriOrder = shopifyOrderItem;
      }
    })
  })

  return json({
    bizOrderList: resDataList || []
  });
}

export const action = async ({request}) => {
  const {admin} = await authenticate.admin(request);

  console.log('收到action通知，admin:', admin);
  console.log('收到action通知，request:', request);

  return json({
    tempList: [{id: 'test', name: '测试使用'}],
  });
};


export default function Index() {
  // const {bizOrderList} = useLoaderData();
  // console.log('打印bizOrderList：', bizOrderList)

  const [bizOrderList, setBizOrderList] = useState([])

  const {selectedResources, allResourcesSelected, handleSelectionChange} =
    useIndexResourceState(bizOrderList);

  /* -------------------------------- */
  const [itemStrings, setItemStrings] = useState([
    '所有',
    '已同步',
    '未同步',
  ]);

  const [curSyncStatus, setCurSyncStatus] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const fetchData = async () => {
      console.log('开始请求');
      setLoading(true)
      const res = await fetch('api/syncList?syncStatus=' + curSyncStatus);
      const resJson = await res.json();
      setBizOrderList(resJson || [])
      setLoading(false)
      console.log('打印结果：', resJson)
    }

    fetchData();
  },[curSyncStatus])

  const tabs: TabProps[] = itemStrings.map((item, index) => ({
    content: item,
    index,
    onAction: () => {
      if (item == '已同步') {
        setCurSyncStatus('1')
      }else if (item == '未同步') {
        setCurSyncStatus('0')
      }else {
        setCurSyncStatus('')
      }
    },
    id: `${item}-${index}`,
    isLocked: index === 0,
    actions: []
  }));

  const [selected, setSelected] = useState(0);
  const {mode, setMode} = useSetIndexFiltersMode();
  const onHandleCancel = () => {
  };

  const [queryValue, setQueryValue] = useState('');

  return (
    <Page
      fullWidth={true}
      title={"运单同步"}
      // primaryAction={
      //   {
      //     content: "导出待发货22",
      //     accessibilityLabel: "Export product list",
      //     onAction: async () => {
      //       shopify.toast.show('点击导出待发货');
      //       const sessionToken = await appBridge.idToken();
      //       console.log('看看idToken：',sessionToken)
      //     }
      //   }
      // }
      // secondaryActions={[
      //   {
      //     content: "导入发货单12",
      //     accessibilityLabel: "Export product list",
      //   },
      // ]}
    >
      <Card padding="0">
        <IndexFilters
          queryValue={queryValue}
          queryPlaceholder="搜索订单"
          onQueryChange={setQueryValue}
          onQueryClear={() => setQueryValue('')}
          cancelAction={{
            onAction: onHandleCancel,
            disabled: false,
            loading: false,
          }}
          canCreateNewView={false}
          hideFilters={true}
          tabs={tabs}
          selected={selected}
          onSelect={setSelected}
          mode={mode}
          setMode={setMode}
          showEditColumnsButton
          loading={loading}
        />
        <IndexTable
          selectedItemsCount={
            selectedResources.length == bizOrderList.length ? 'All' : selectedResources.length
          }
          onSelectionChange={(selectionType: SelectionType, toggleType: boolean, selection?: string | Range, position?: number) => {
            handleSelectionChange(selectionType as any, toggleType, selection, position)
          }}
          itemCount={bizOrderList.length}
          headings={[
            {title: "订单"},
            {title: "客户"},
            {title: "下单时间"},
            {title: "同步状态"},
            {title: "目的地址"},
            {title: "运输公司"},
            {title: "运单号"},
            {title: "转单号"},
            {title: "最新运踪"},
          ]}
          selectable={true}
          tabs={tabs}
          selected={selected}
        >
          {bizOrderList.length > 0 && bizOrderList.map((bizOrderItem) => {
            return <IndexTable.Row
              id={bizOrderItem.id}
              position={bizOrderItem.id}
              selected={selectedResources.includes(bizOrderItem.id)}
            >
              <IndexTable.Cell>{bizOrderItem.oriOrder.name}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.oriOrder.customer && bizOrderItem.oriOrder.customer.first_name + bizOrderItem.oriOrder.customer.last_name}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.oriOrder.created_at}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.syncStatus == 1 ? <Badge tone="success">已同步</Badge> : <Badge tone="warning">未同步</Badge>}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.oriOrder.shipping_address.address1}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.trackCompany}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.trackNumber}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.transferNo}</IndexTable.Cell>
              <IndexTable.Cell>{bizOrderItem.lastTrackStr}</IndexTable.Cell>
            </IndexTable.Row>
          })}
        </IndexTable>
        {/*<Pagination*/}
        {/*  hasPrevious*/}
        {/*  onPrevious={() => {*/}
        {/*    console.log('Previous');*/}
        {/*  }}*/}
        {/*  hasNext*/}
        {/*  onNext={() => {*/}
        {/*    console.log('Next');*/}
        {/*  }}*/}
        {/*/>*/}
      </Card>
    </Page>
  );
}
